package com.pkx.guide.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pkx.guide.common.util.DateUtils;
import com.pkx.guide.common.util.IpUtils;
import com.pkx.guide.common.util.StringUtils;
import com.pkx.guide.info.entity.TInfoGuide;
import com.pkx.guide.info.entity.TInfoGuideImg;
import com.pkx.guide.info.entity.TInfoGuideStatus;
import com.pkx.guide.info.entity.TInfoNetworkConfig;
import com.pkx.guide.info.service.TInfoGuideImgService;
import com.pkx.guide.info.service.TInfoGuideService;
import com.pkx.guide.info.service.TInfoGuideStatusService;
import com.pkx.guide.info.service.TInfoNetworkConfigService;
import com.pkx.guide.qianfeng.service.QianFengPlayLedService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 情报板心跳
 */
@Configuration
@ConditionalOnProperty(name="task.enable", havingValue = "true")
@Slf4j
public class GuideHeartbeat {

    @Resource
    private TInfoGuideService guideService;

    @Resource
    private TInfoGuideStatusService infoGuideStatusService;

    @Resource
    private TInfoNetworkConfigService infoNetworkConfigService;

    @Resource
    private QianFengPlayLedService qianFengPlayLedService;

    @Resource
    private TInfoGuideImgService tInfoGuideImgService;


    @Scheduled(initialDelayString = "${task.initialDelay}", fixedRateString = "${task.fixedRate}")
    public void heartbeat() throws Exception {
        log.info("情报板心跳检测开始执行");
        // 获取情报板集合
        List<TInfoGuide> guideList = guideService.list(new QueryWrapper<TInfoGuide>().lambda().eq(TInfoGuide::getDelFlg, 0));
        if (guideList == null || guideList.size() == 0){
            return;
        }
        TInfoGuideStatus infoGuideStatus = null;
        // TRecordGuideStatus recordGuideStatus = null;
        String currentTimeStr = DateUtils.getCurrentTimeStr();
        // 查询乾丰上位机网络配置
        TInfoNetworkConfig networkConfig = infoNetworkConfigService.selectByGuideType(1);
        JSONArray jsonArray = new JSONArray();
        JSONObject dataJson = null;
        for (TInfoGuide guide : guideList) {
            if (StringUtils.isEmpty(guide.getGuidIp())){
                continue;
            }
            infoGuideStatus = new TInfoGuideStatus();
            // recordGuideStatus = new TRecordGuideStatus();
            // 是否可以ping通
            boolean result = IpUtils.ping(guide.getGuidIp());
            infoGuideStatus.setGuideId(guide.getId());
            infoGuideStatus.setGuidIp(guide.getGuidIp());
            infoGuideStatus.setOfflineTime(currentTimeStr);
            infoGuideStatus.setOfflineStatus(result? "0": "1");
            if (infoGuideStatus.getOfflineStatus().equals("1")){
                log.error("ip:{}，设备网络不通"+guide.getGuidIp());
            }
            // infoGuideStatus.setPictureUrl("");
            // infoGuideStatus.setImgNum(null);
            // 查询情报板显示内容
            if (result && guide.getGuideType() != null && guide.getGuideType() == 1){
                dataJson = new JSONObject();
                dataJson.put("ip", guide.getGuidIp());
                jsonArray.add(dataJson);
            }
            // 保存或更新情报板状态信息
            infoGuideStatusService.saveOrUpdateGuideStatus(infoGuideStatus);
        }
        JSONObject param = new JSONObject();
        param.put("user", networkConfig.getUsername());
        param.put("pwd", networkConfig.getPassword());
        param.put("cmd", "2");
        param.put("data", jsonArray);
        String ledResult = qianFengPlayLedService.controlLed(networkConfig.getIp(), networkConfig.getPort(), param.toJSONString());
        JSONObject jsonResult = JSONObject.parseObject(ledResult);
        if (jsonResult != null && (jsonResult.getInteger("code") == 0 || jsonResult.getInteger("code") == 3)){
            JSONArray data = JSONArray.parseArray(jsonResult.getString("data"));
            log.info("执行状态更新");
            infoGuideStatusService.updateGuideStatus(data);

        }

        log.info("情报板心跳检测结束执行");
    }

    /**
     * 根据节目编号/车道号获取图片地址
     * @param imgNum
     * @param laneNo
     * @param guideImgList
     * @return
     */
    private String getGuideImg(Integer imgNum, Integer laneNo, List<TInfoGuideImg> guideImgList){
        for (TInfoGuideImg guideImg : guideImgList) {
            if (imgNum.equals(guideImg.getImgNum()) && laneNo.equals(guideImg.getLaneNo())){
                return guideImg.getImgUrl();
            }
        }
        return null;
    }
}
